<?php

namespace App\Services;

use App\Models\ClassifyTemplate;

class ClassifyTemplateService extends BaseService
{
    /**
     * 分类模板列表
     */
    public function getList($request, $perPage = 0)
    {
        $thisQuery = ClassifyTemplate::query()
            ->leftJoin('users as u', 'u.id', '=', 'classify_templates.creator_id');
        if($request->filled('keyword')){
            $keyword = $request->input('keyword');
            $thisQuery->where('title', 'like', "%{$keyword}%")->orWhere('id', '=', $keyword);
        }
        $list = $thisQuery->orderBy('id')->select('classify_templates.*', 'u.nickname as creator')->paginate($perPage);

        if ($list->isEmpty())  return [];

        return $this->removeNoUsedPageParams($list->toArray());
    }


    /**
     * 保存模板数据
     */
    public function saveData($params)
    {
        if ($params['id']) {
            $classifyTemplate = ClassifyTemplate::query()->where('id', $params['id'])->first();
            $content = '修改分类模板';
        } else {
            $classifyTemplate = new ClassifyTemplate();
            $content = '新增分类模板';
        }
        $classifyTemplate->title = $params['title'];
        $classifyTemplate->creator_id = user_id();
        if (!$classifyTemplate->save()) return false;

        CommonService::addActionLog($content, "数据id={$classifyTemplate->id}");

        return $classifyTemplate->id;
    }

    /**
     * 更新一条数据
     */
    public function updateData($id, array $params)
    {
        $classifyTemplate = ClassifyTemplate::query()->where('id', $id)->first();

        $classifyTemplate->title = $params['title'];
        $classifyTemplate->sort  = $params['sort'];
        $classifyTemplate->creator_id = user_id();

        CommonService::addActionLog('更新一条分类模板', "数据id={$id}");

        return $classifyTemplate->save();
    }

    /**
     * 获取软删除的数据列表
     */
    public function getRecycles($request): array
    {
        $thisQuery = ClassifyTemplate::onlyTrashed();

        if ($request->filled('keyword')) { //判断参数是否存在并且不为空
            $keyword = $request->input('keyword');
            $thisQuery->where('title', 'like', "%{$keyword}%")->orWhere('id', '=', $keyword); //由于不同的表字段不同，所以单独拿出来
        }

        return $this->formatRecycleData($request, $thisQuery);
    }


}
